﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernateLib = NHibernate;
using YasharEl.Infrastructure.ObjectFactory;
using YasharEl.Infrastructure.Diagnostics.Logging;

namespace YasharEl.Infrastructure.PersistenceModel.NHibernate.Diagnostics.Logging
{
    public class NHibernateLoggerFactory : NHibernateLib.ILoggerFactory
    {
        public NHibernateLib.IInternalLogger LoggerFor(Type type)
        {
            Type loggerOpenGenericType = typeof(ILogger<>);
            Type loggerClosedType = loggerOpenGenericType.MakeGenericType(new Type[] { type });
            ILogger logger = (ILogger)DependencyContainer.Resolve(loggerClosedType);

            return new NHibernateLogger(logger);
        }

        public NHibernateLib.IInternalLogger LoggerFor(string keyName)
        {
            ILogger namedLogger = null;
            if (!DependencyContainer.TryResolve<ILogger>(out namedLogger, keyName))
            {
                // Register factory method witn named logger resolution.
                FactoryMethod factoryMethodForNamedLogger = new FactoryMethod((type, resolver, requestedType, key) =>
                {
                    return resolver.Resolve<ILoggerFactory>().Create(key);
                }
                );
                DependencyContainer
                    .Resolve<IDependencyRegistrar>()
                    .RegisterFactory(typeof(ILogger), keyName, factoryMethodForNamedLogger);
            }

            if (namedLogger == null)
            {
                namedLogger = DependencyContainer.Resolve<ILogger>(keyName);
            }

            return new NHibernateLogger(namedLogger);
        }
    }
}
